/*
Copyright 2025 PerfXLab (Beijing) Technologies Co., Ltd.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "OpenSparseBLAS_func.h"
#include <complex>

// -----------------------------------------------------------------------------
// 通用模板：
//   x[i]  = y[idx * incy];   // 抽取
//   y[idx * incy] = T{};      // 置零
// -----------------------------------------------------------------------------
template <typename T>
inline void OpenSpB_gather_zero(
    int nz,
    T* y, int incy,
    T* x, const int* indx,
    OpenSpB_base_type index_base)
{
    if (nz <= 0 || incy <= 0) return;
    const int base = (index_base == OPENSPBLAS_ONE_BASE) ? 1 : 0;
    for (int i = 0; i < nz; ++i) {
        const int idx = indx[i] - base;
        const int pos = idx * incy;
        x[i]        = y[pos];   // gather
        y[pos]      = T{};      // zero‐out
    }
}

/*-------------------------------- float -------------------------------------*/
void OpenSpB_sgther_zero(
    int nz,
    float* y, int incy,
    float* x, const int* indx,
    OpenSpB_base_type index_base)
{
    OpenSpB_gather_zero<float>(nz, y, incy, x, indx, index_base);
}

/*-------------------------------- double ------------------------------------*/
void OpenSpB_dgther_zero(
    int nz,
    double* y, int incy,
    double* x, const int* indx,
    OpenSpB_base_type index_base)
{
    OpenSpB_gather_zero<double>(nz, y, incy, x, indx, index_base);
}

/*---------------------------- complex<float> --------------------------------*/
void OpenSpB_cgther_zero(
    int nz,
    void* y, int incy,
    void* x, const int* indx,
    OpenSpB_base_type index_base)
{
    OpenSpB_gather_zero<std::complex<float>>(
        nz,
        static_cast<std::complex<float>*>(y),
        incy,
        static_cast<std::complex<float>*>(x),
        indx,
        index_base);
}

/*--------------------------- complex<double> --------------------------------*/
void OpenSpB_zgther_zero(
    int nz,
    void* y, int incy,
    void* x, const int* indx,
    OpenSpB_base_type index_base)
{
    OpenSpB_gather_zero<std::complex<double>>(
        nz,
        static_cast<std::complex<double>*>(y),
        incy,
        static_cast<std::complex<double>*>(x),
        indx,
        index_base);
}
